package 多线程;

/**
 * 保证A执行完后，B执行，使用对象锁
 * 同一时间只有一个线程持有一个锁
 */
public class ObjectLock {
    private static Object lock = new Object();

    static class ThreadA implements Runnable {
        @Override
        public void run() {
            synchronized (lock){
                for (int i = 0; i < 100; i++) {
                    System.out.println("Thread A "+i);
                }
            }

        }
    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {
            synchronized (lock){
                for (int i = 0; i < 100; i++) {
                    System.out.println("Thread B "+i);
                }
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new NoneLock.ThreadA()).start();
        //主线程使用sleep方法睡眠10毫秒，为了防止线程B先得到锁
        Thread.sleep(10);
        new Thread(new NoneLock.ThreadB()).start();
    }


}
